package com.qf.taobei.controller;

import com.qf.taobei.entity.RespBean;
import com.qf.taobei.entity.User;
import com.qf.taobei.service.UserService;
import com.qf.taobei.utils.EmailUtils;
import com.qf.taobei.utils.MyFileUtils;
import com.qf.taobei.utils.OssUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;

@Api(tags = "用户模块")
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    //测试阿里云对象存储功能
    @PostMapping(value = "/upload",consumes = "multipart/*",
            headers = "content-type=multipart/form-data")
    public RespBean upload(MultipartFile file) throws IOException {
        String upload = OssUtils.upload(file.getOriginalFilename(), file.getInputStream());
        return RespBean.respSuccess(upload);
    }

    //获取用户账户余额
    @GetMapping("/getSessionUser")
    public RespBean queryUserAccount(HttpSession session){
        User user = (User) session.getAttribute("user");
        return RespBean.respSuccess("成功",user);
    }

    //用户更新头像
    @PostMapping(value = "/updateImg",consumes = "multipart/*",
            headers = "content-type=multipart/form-data")
    public RespBean updateImg(HttpSession session,MultipartFile file) throws IOException {
        //先从session中获取用户信息
        User user = (User) session.getAttribute("user");
        //调用阿里云工具类上传图片
        String url = OssUtils.upload(file.getOriginalFilename(), file.getInputStream());
        user.setImgUrl(url);
        Integer res = userService.updateUserImg(user.getId(),url);
        if (res == 0){
            return RespBean.respError("系统繁忙");
        }
        //更新session中用户信息
        user = userService.queryUserByTel(user.getTel());
        session.setAttribute("user",user);
        return RespBean.respSuccess("更新成功",user);
    }

    /**
     * 手机号+密码 登录
     * @param user
     * @return
     */
    @PostMapping("/login")
    public RespBean login(HttpSession session,User user,String verifyCode){
        String code = (String) session.getAttribute("code");
        if (!code.equalsIgnoreCase(verifyCode)){
            return RespBean.respError("验证码错误");
        }
        User rs = userService.login(user);
        if (rs == null){
            return RespBean.respError("用户名或密码有误");
        }
        session.setAttribute("user",rs);
        return RespBean.respSuccess("登录成功",rs);

    }

    //手机号+邮箱验证码登录
    @PostMapping("/emailLogin")
    public RespBean emailLogin(HttpSession session,String tel,String code){
        Map<String, Date> map = (Map<String, Date>) session.getAttribute("loginCode");
        //如果没点发送验证码就点击登录，直接告诉用户验证码错误
        if (map == null){
            return RespBean.respError("验证码不正确");
        }
        Date time = map.get(code);
        if (time == null){
            return RespBean.respError("验证码不正确");
        }
        Date date = new Date();
        //把正确和过期验证码移除
//        map.remove(code);
//        session.setAttribute("loginCode",map);
        //判断验证码是否超过3分钟
        if (date.getTime() - time.getTime() >= 3*60*1000){
            //验证码失效把储存的内容移除
            return RespBean.respError("验证码已失效");
        }
        //验证码正确直接删除发送的所有验证码
//        session.removeAttribute("loginCode");
        User user = userService.queryUserByTel(tel);
        //存储用户到session作用域中
        session.setAttribute("user",user);
        return RespBean.respSuccess("登录成功",user);
    }

    /**
     * 用户注册
     * @param user
     * @return
     */
//    @PostMapping(value = "/register",consumes = "multipart/*",
//            headers = "content-type=multipart/form-data")
    @PostMapping("/register")
    public RespBean register(HttpSession session, User user,String code) {
        //先校验邮箱验证码是否输入正确
        Map<String,Date> map = (Map<String,Date>) session.getAttribute("registerCode");
        Date time = map.get(code);
        if (time == null){
            return RespBean.respError("验证码错误");
        }
        Date date = new Date();
        //判断验证码是否超过3分钟
        if (date.getTime() - time.getTime() >= 3*60*1000){
            //验证码失效把储存的内容移除
            map.remove(code);
            return RespBean.respError("验证码已失效");
        }
        //获取用户注册时间
        user.setRegisterTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        //把用户信息存储到数据库中
        Integer res = userService.register(user);
        if (res == 0){
            return RespBean.respError("系统繁忙!");
        }
        return RespBean.respSuccess("注册成功！");
    }


    /**
     * 修改个人信息
     * @param user
     * @return
     */
    @PostMapping("/update")
    public RespBean updateInfo(HttpSession session,User user){
        User us = (User) session.getAttribute("user");
        user.setId(us.getId());
        Integer rs = userService.updateInfo(user);
        if (rs == 0){
           return RespBean.respError("系统繁忙");
        }
        user = userService.queryUserByTel(us.getTel());
        return RespBean.respSuccess("修改成功",user);
    }

    /**
     * 用户注销登录
     * @param session
     * @return
     */
    @GetMapping("/logout")
    public RespBean logout(HttpSession session){
        session.removeAttribute("user");
        return RespBean.respSuccess("注销成功");
    }

    /**
     * 删除用户
     * @param id
     * @return
     */
    @PostMapping("/delUser")
    public RespBean delUserByUid(Integer id){
        Integer res = userService.delUser(id);
        if (res == 0){
            return RespBean.respError("系统繁忙");
        }
        return RespBean.respSuccess("删除成功");
    }


    /**
     * 多条件查询用户列表
     * @param user
     * @return
     */
    @GetMapping("/searchUser")
    public RespBean searchUser(User user){
        List<User> userList = userService.searchUser(user);
        return RespBean.respSuccess("查询成功",userList);
    }

    //校验旧密码是否正确
    @PostMapping("/checkPwd")
    public RespBean checkPwd(HttpSession session,String password){
        User user = (User) session.getAttribute("user");
        if (user.getPassword().equals(password)){
            return RespBean.respSuccess("旧密码正确");
        }
        return RespBean.respError("旧密码输入错误");
    }

    //校验手机号是否已经注册
    @GetMapping("/checkTel")
    public RespBean checkTel(String tel){
        boolean flag = userService.checkTel(tel);
        if (flag){
            //可用
            return RespBean.respSuccess("手机号可用");
        }
        return RespBean.respError("手机号已经注册");
    }

    //修改绑定邮箱
    @PostMapping("/updateEmail")
    public RespBean updateEmail(HttpSession session,String email,String code){
        User user = (User) session.getAttribute("user");
        //获取保存在session中的验证码
        Map<String, Date> map = (Map<String, Date>) session.getAttribute("editEmailCheckCode");
        if (map == null){
            return RespBean.respError("验证码错误");
        }
        Date time = map.get(code);
        if (time == null){
            return RespBean.respError("验证码错误");
        }
        //判断验证码是否已过期
        Date date = new Date();
        //判断验证码是否超过3分钟
        if (date.getTime() - time.getTime() >= 3*60*1000){
            //验证码失效把储存的内容移除
            map.remove(code);
            return RespBean.respError("验证码已失效");
        }
        //验证码没问题，对邮箱进行修改
        user.setEmail(email);
        Integer res = userService.updateInfo(user);
        if (res == 0){
            return RespBean.respError("系统繁忙");
        }
        //修改成功，把session清空，让用户重新登录
        session.removeAttribute("user");
        return RespBean.respSuccess("修改成功");

    }

    //修改手机号时判断新手机号是否已经存在（如果没修改则直接返回已经存在，不做修改）
    @PostMapping("/checkNewTel")
    public RespBean checkNewTel(HttpSession session,String tel){
        User user = (User) session.getAttribute("user");
        if (user.getTel().equals(tel)){
            //如果没做修改，直接返回已经存在
            return RespBean.respError("已经存在");
        }
        //去数据库中查询
        User u = userService.queryUserByTel(tel);
        if (u != null){
            //能通过手机号查找到用户，说明已经被使用
            return RespBean.respError("已经存在");
        }
        //走到这说明没有与之冲突的手机号
        return RespBean.respSuccess("可用");
    }

    //修改密码
    @PostMapping("/updatePwd")
    public RespBean updatePwd(HttpSession session,String pwd){
        User user = (User) session.getAttribute("user");
        Integer res = userService.updatePwd(user.getId(),pwd);
        if (res == 0){
            return RespBean.respError("系统繁忙");
        }
        //清除session中的用户信息
        session.removeAttribute("user");
        return RespBean.respSuccess("修改成功");
    }

    //修改注册时手机号
    @PostMapping("/updateTel")
    public RespBean updateTel(HttpSession session,String tel,String code){
        User user = (User) session.getAttribute("user");
        Map<String, Date> map = (Map<String, Date>) session.getAttribute("editTelCheckEmailCode");
        Date time = map.get(code);
        if (time == null){
            return RespBean.respError("验证码错误");
        }
        Date date = new Date();
        //判断验证码是否超过3分钟
        if (date.getTime() - time.getTime() >= 3*60*1000){
            //验证码失效把储存的内容移除
            map.remove(code);
            session.setAttribute("editTelCheckEmailCode",map);
            return RespBean.respError("验证码已失效");
        }
        Integer res = userService.updateTel(user.getId(),tel);
        if (res == 0){
            return RespBean.respError("系统繁忙");
        }
        //清除保存在session中的用户对象，让用户重新登录
        session.removeAttribute("user");
        return RespBean.respSuccess("修改成功");
    }

    //用户充值
    @ApiOperation("用户充值")
    @PostMapping("/updateAccount")
    public RespBean updateAccount(HttpSession session,Double money){
        User user = (User) session.getAttribute("user");
        Integer res = userService.updateAccount(user.getId(),money);
        if (res == 0){
            return RespBean.respError("系统繁忙");
        }
        user = userService.queryUserByTel(user.getTel());
        session.setAttribute("user",user);
        return RespBean.respSuccess("成功",user);
    }

    //修改绑定邮箱时发送验证码
    @GetMapping("/editEmailCheckCode")
    public RespBean editEmailCheckCode(HttpSession session){
        User user = (User)session.getAttribute("user");
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i <4; i++) {
            sb.append(new Random().nextInt(10));
        }
        String code = sb.toString();
        Map<String, Date> map = (Map<String, Date>) session.getAttribute("editEmailCheckCode");
        if (map == null){
            map = new HashMap<>();
        }
        map.put(code,new Date());
        session.setAttribute("editEmailCheckCode",map);
        EmailUtils.sendEmail(user,code);
        return RespBean.respSuccess("验证码发送成功");
    }

    //修改手机号时验证邮箱发送验证码
    @GetMapping("/editTelCheckEmailCode")
    public RespBean editTelCheckEmailCode(HttpSession session){
        User user = (User)session.getAttribute("user");
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i <4; i++) {
            sb.append(new Random().nextInt(10));
        }
        String code = sb.toString();
        Map<String, Date> map = (Map<String, Date>) session.getAttribute("registerCode");
        if (map == null){
            map = new HashMap<>();
        }
        map.put(code,new Date());
        session.setAttribute("editTelCheckEmailCode",map);
        EmailUtils.sendEmail(user,code);
        return RespBean.respSuccess("验证码发送成功");
    }

    //注册时发送验证码
    @PostMapping("/registerCode")
    public RespBean registerBean(HttpSession session,String username,String email){
        User user = new User();
        user.setUsername(username);
        user.setEmail(email);
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i <4; i++) {
            sb.append(new Random().nextInt(10));
        }
        String code = sb.toString();
        Map<String, Date> map = (Map<String, Date>) session.getAttribute("registerCode");
        if (map == null){
            map = new HashMap<>();
        }
        map.put(code,new Date());
        session.setAttribute("registerCode",map);
        EmailUtils.sendEmail(user,code);
        return RespBean.respSuccess("验证码发送成功");
    }

    //登录时发送验证码
    @GetMapping("/loginCode")
    public RespBean loginCode(HttpSession session,String tel){
        //先去查询这个手机号绑定的邮箱
        User user = userService.queryUserByTel(tel);
        if (user == null){
            //该手机号未注册
            return RespBean.respError("手机号未注册");
        }
        //发送验证码
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i <4; i++) {
            sb.append(new Random().nextInt(10));
        }
        String code = sb.toString();
        Map<String, Date> map = (Map<String, Date>) session.getAttribute("loginCode");
        if (map == null){
            map = new HashMap<>();
        }
        map.put(code,new Date());
        session.setAttribute("loginCode",map);
        EmailUtils.sendEmail(user,code);
        return RespBean.respSuccess("发送成功");
    }

    //找回密码时发送验证码
    @GetMapping("retrieveCode")
    public RespBean retrievePCode(HttpSession session,String tel){
        //先去查询这个手机号绑定的邮箱
        User user = userService.queryUserByTel(tel);
        if (user == null){
            //该手机号未注册
            return RespBean.respError("手机号未注册");
        }
        //发送验证码
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i <4; i++) {
            sb.append(new Random().nextInt(10));
        }
        String code = sb.toString();
        Map<String, Date> map = (Map<String, Date>) session.getAttribute("retrieveCode");
        if (map == null){
            map = new HashMap<>();
        }
        map.put(code,new Date());
        session.setAttribute("retrieveCode",map);
        EmailUtils.sendEmail(user,code);
        return RespBean.respSuccess("发送成功");
    }

    //找回密码时校验验证码
    @PostMapping("/checkEmailCode")
    public RespBean checkEmailCode(HttpSession session,String code){
        Map<String,Object> map = (Map<String,Object>) session.getAttribute("retrieveCode");
        Date time = (Date) map.get(code);
        if (time == null){
            return RespBean.respError("验证码不正确");
        }
        Date date = new Date();
        //判断验证码是否超过3分钟
        if (date.getTime() - time.getTime() >= 3*60*1000){
            //验证码失效把储存的内容移除
            map.remove(code);
            return RespBean.respError("验证码已失效");
        }
        return RespBean.respSuccess("验证码正确");
    }

    /**
     * 发送邮件验证码
     * @param email
     * @return
     */
    @PostMapping("/sendEmail")
    public RespBean sendEmail(HttpSession session,String email){
//        User user = userService.getUserByEmail(email);
//        if (user == null){
//            return RespBean.respError("邮箱未绑定账户");
//        }
        User user = new User();
        user.setEmail(email);
        user.setUsername("小豆丁");
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i <4; i++) {
            sb.append(new Random().nextInt(10));
        }
        String code = sb.toString();
        Map<String, Object> map = new HashMap<>();
        map.put("code",code);
        map.put("time",new Date());
        //把验证码和创建时间存到session中
        session.setAttribute("codeMap",map);
        EmailUtils.sendEmail(user,code);
        return RespBean.respSuccess("验证码发送成功");
    }

    /**
     * 校验邮箱验证码是否正确
     * @param code
     * @return
     */
//    @PostMapping("/checkEmailCode")
//    public RespBean checkEmailCode(HttpSession session,String code){
//        Map<String, Object> codeMap = (Map<String, Object>) session.getAttribute("codeMap");
//        //如果用户没发送验证码就验证
//        if (codeMap == null){
//            return RespBean.respError("无效的验证码");
//        }
//        Date time = (Date) codeMap.get("time");
//        Date date = new Date();
//        //判断验证码是否超过3分钟
//        if (date.getTime() - time.getTime() >= 3*60*1000){
//            //验证码失效把储存的内容移除
//            session.removeAttribute("codeMap");
//            return RespBean.respError("验证码已失效");
//        }
//        String s = (String) codeMap.get("code");
//        if (!s.equals(code)){
//            return RespBean.respError("验证码不正确");
//        }
//        return RespBean.respSuccess("验证码正确");
//    }

    /**
     * 获取登录验证码
     * @param session
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @GetMapping("/verifyCode")
    public void getCode(HttpSession session, HttpServletResponse response) throws IOException {
        int width = 100;
        int height = 50;
        //1.生成一个图片对象
        BufferedImage bImage = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        //2.获取画笔
        Graphics graphics = bImage.getGraphics();
        //3.选择颜色
        graphics.setColor(Color.WHITE);
        //4.填充背景颜色
        graphics.fillRect(0,0,width,height);
        //5.重新选择画笔颜色
        graphics.setColor(Color.RED);
        //6.选择字体样式
        graphics.setFont(new Font("宋体",Font.BOLD,20));
        //7.生成随机数
        Random ran = new Random();
        String code;
        //存储验证码
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 4; i++) {
            code = ran.nextInt(10)+"";
            sb.append(code);
            //8.写入数字
            graphics.drawString(code,15+i*20,ran.nextInt(10)+30);
        }
        //把验证码存放在session作用域中    --  会话级别
        session.setAttribute("code",sb.toString());
        //9.重新选择画笔颜色
        graphics.setColor(Color.GRAY);
        //10.绘制干扰线
        for (int i = 0; i < 10; i++) {
            //x的开始，y的开始，x的结束，y的结束
            graphics.drawLine(ran.nextInt(width),ran.nextInt(height),ran.nextInt(width),ran.nextInt(height));
        }
        //11.把绘制好的验证码响应回前端
        ImageIO.write(bImage,"jpg",response.getOutputStream());
    }

}
